﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TunnelBackground
{
    public partial class FireCommForm : Form
    {
        public FireCommForm()
        {
            InitializeComponent();
        }

        private void bwSP_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                COM.SP.Open();
            }
            catch { }
            COM.SP.DataReceived += SP_DataReceived;
            while (true)
            {; }
        }

        private void SP_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            System.Threading.Thread.Sleep(200);
            byte[] ReDates = new byte[COM.SP.BytesToRead];
            COM.SP.Read(ReDates, 0, ReDates.Length);
            bwSP.ReportProgress(10, ReDates);
        }

        private void bwSP_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            byte[] ReDatas = e.UserState as byte[];
            //var reDataList= ReDatas.ToList();
            ////去掉包头的0x0D和0x0A
            //reDataList.Remove(0x0D);
            //reDataList.Remove(0x0A);
            //reDataList.Remove(0x0D);
            //reDataList.Remove(0x0A);


            string AlarmString = System.Text.Encoding.Default.GetString(ReDatas);
            //删除字符串中的0X0D和0X0A字符
            //AlarmString = AlarmString.Replace("\r\n", string.Empty);
            SendMessageToUI(AlarmString);
        }
        TunnelDCS.DataConnectionServiceClient dsc = new TunnelDCS.DataConnectionServiceClient();
        private void SendMessageToUI(string AlarmString)
        {
            AlarmAnalysis AlarmInfo = new AlarmAnalysis(AlarmString);
            textBox1.Text = AlarmInfo.AlarmType;
            textBox2.Text = AlarmInfo.AlarmTime.ToString();
            textBox3.Text = AlarmInfo.ControlPanel;
            textBox4.Text = AlarmInfo.Card;
            textBox5.Text = AlarmInfo.Device;


            string deviceId = "";
            string devicetype = "";


            var dtFire = from s1 in FireAlarmTable.dtFireAlarmTable.AsEnumerable()
                         where ((s1.Field<string>("ControlPanel") == AlarmInfo.ControlPanel) && (s1.Field<string>("Card") == AlarmInfo.Card) && (s1.Field<string>("Device") == AlarmInfo.Device))
                         select s1;
            foreach (var item in dtFire)
            {
                deviceId = item["DeviceID"].ToString();
                devicetype = item["TypeID"].ToString();
            }

            textBox6.Text = textBox6.Text + AlarmString + "\r\n";
            textBox7.Text = textBox7.Text + AlarmInfo.AlarmType + " " + AlarmInfo.AlarmTime.ToString() + " " + AlarmInfo.ControlPanel + " " + AlarmInfo.Card + " " + AlarmInfo.Device + " " + deviceId + " " + devicetype + "\r\n";

            switch (devicetype)
            {
                case "FD":
                    {
                        if (AlarmInfo.AlarmType == "手报")
                        {
                            try
                            {
                                dsc.ChangeDeviceStatusAsync(deviceId, "041", AlarmInfo.AlarmType, devicetype, AlarmInfo.AlarmTime.ToString());
                                ChangeDbDeviceStatus(deviceId, "041", AlarmInfo.AlarmType);
                                InsertDbAlarm(deviceId, AlarmInfo.AlarmTime, AlarmInfo.AlarmType);
                            }
                            catch { }
                        }
                        if (AlarmInfo.AlarmType == "恢复")
                        {
                            try
                            {
                                dsc.ChangeDeviceStatusAsync(deviceId, "040", "正常", devicetype, AlarmInfo.AlarmTime.ToString());
                                ChangeDbDeviceStatus(deviceId, "040", "正常");
                            }
                            catch { }
                        }
                        if (AlarmInfo.AlarmType == "故障")
                        {
                            try
                            {
                                dsc.ChangeDeviceStatusAsync(deviceId, "042", "故障", devicetype, AlarmInfo.AlarmTime.ToString());
                                ChangeDbDeviceStatus(deviceId, "042", "故障");
                                InsertDbAlarm(deviceId, AlarmInfo.AlarmTime, AlarmInfo.AlarmType);
                            }
                            catch { }
                        }
                    }
                    break;
                case "Somke":
                    {
                        if (AlarmInfo.AlarmType == "火警")
                        {
                            try
                            {
                                dsc.ChangeDeviceStatusAsync(deviceId, "045", AlarmInfo.AlarmType, devicetype, AlarmInfo.AlarmTime.ToString());
                                ChangeDbDeviceStatus(deviceId, "045", AlarmInfo.AlarmType);
                                InsertDbAlarm(deviceId, AlarmInfo.AlarmTime, AlarmInfo.AlarmType);
                            }
                            catch { }
                        }
                        if (AlarmInfo.AlarmType == "恢复")
                        {
                            try
                            {
                                dsc.ChangeDeviceStatusAsync(deviceId, "046", "正常", devicetype, AlarmInfo.AlarmTime.ToString());
                                ChangeDbDeviceStatus(deviceId, "046", "正常");
                            }
                            catch { }
                        }
                        if (AlarmInfo.AlarmType == "故障")
                        {
                            try
                            {
                                dsc.ChangeDeviceStatusAsync(deviceId, "047", "故障", devicetype, AlarmInfo.AlarmTime.ToString());
                                ChangeDbDeviceStatus(deviceId, "047", "故障");
                                InsertDbAlarm(deviceId, AlarmInfo.AlarmTime, AlarmInfo.AlarmType);
                            }
                            catch { }
                        }
                    }
                    break;
                case "Fiber":
                    {
                        if (AlarmInfo.AlarmType == "与组")
                        {
                            try
                            {
                                dsc.ChangeDeviceStatusAsync(deviceId, "048", "高温", devicetype, AlarmInfo.AlarmTime.ToString());
                                ChangeDbDeviceStatus(deviceId, "048", "高温");
                                InsertDbAlarm(deviceId, AlarmInfo.AlarmTime, "高温");
                            }
                            catch { }
                        }
                        if (AlarmInfo.AlarmType == "恢复")
                        {
                            try
                            {
                                dsc.ChangeDeviceStatusAsync(deviceId, "049", "正常", devicetype, AlarmInfo.AlarmTime.ToString());
                                ChangeDbDeviceStatus(deviceId, "049", "正常");
                            }
                            catch { }
                        }
                        if (AlarmInfo.AlarmType == "故障")
                        {
                            try
                            {
                                dsc.ChangeDeviceStatusAsync(deviceId, "050", "故障", devicetype, AlarmInfo.AlarmTime.ToString());
                                ChangeDbDeviceStatus(deviceId, "050", "故障");
                                InsertDbAlarm(deviceId, AlarmInfo.AlarmTime, AlarmInfo.AlarmType);
                            }
                            catch { }
                        }
                    }
                    break;
            }

        }

        /// <summary>
        /// 修改数据库中状态表
        /// </summary>
        /// <param name="deviceId">设备ID</param>
        /// <param name="statusId">状态ID</param>
        /// <param name="statusDescription">状态描述</param>
        private void ChangeDbDeviceStatus(string deviceId, string statusId, string statusDescription)
        {
            SqlDBHelper sdh = new SqlDBHelper();
            string updatesql = "update M_Device set DeviceStatusID='" + statusId + "',UpdateTime='" + DateTime.Now.ToString() + "' where DeviceID='" + deviceId + "'";
            sdh.ExecuteCommand(updatesql);
        }
        /// <summary>
        /// 增加报警信息
        /// </summary>
        /// <param name="deviceId">设备ID</param>
        /// <param name="alarmTime">报警时间</param>
        /// <param name="alarmInfo">报警内容</param>
        private void InsertDbAlarm(string deviceId, DateTime alarmTime, string alarmInfo)
        {
            SqlDBHelper sdh = new SqlDBHelper();
            string updatesql = "insert into H_AlarmInfo(AlarmID,DeviceID,AlarmTime,AlarmInfo) values ('" + new GUID().CommandID + "','" + deviceId + "','" + alarmTime.ToString() + "','" + alarmInfo + "')";
            sdh.ExecuteCommand(updatesql);
        }



        private void FireCommForm_Load(object sender, EventArgs e)
        {
            string FireAlarmTableSqlString = "SELECT  R_FireAlarmDevice.ControlPanel, R_FireAlarmDevice.Card, R_FireAlarmDevice.Device, R_FireAlarmDevice.AlarmType, R_FireAlarmDevice.AlarmTime, R_FireAlarmDevice.DeviceID, M_Device.DeviceID AS Expr1, M_Device.DeviceStatusID, M_Device.TypeID FROM R_FireAlarmDevice INNER JOIN M_Device ON R_FireAlarmDevice.DeviceID = M_Device.DeviceID";
            SqlDBHelper sdh = new SqlDBHelper();
            FireAlarmTable.dtFireAlarmTable = sdh.GetTable(FireAlarmTableSqlString);

            FireAlarmServices FAS = new FireAlarmServices();
            ServiceHost fasHost = new ServiceHost(FAS);
            try
            {
                fasHost.Open();
            }
            catch (System.ServiceModel.AddressAlreadyInUseException ex)
            {
                MessageBox.Show("当前数据接口服务地址已被占用，请检查是否开启多个监控程序，详细错误如下：\r\n" + ex.Message);
                Application.Exit();
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据接口服务开启失败，程序将退出，错误编号：\r\n" + ex.Message);
                Application.Exit();
            }


            bwSP.RunWorkerAsync();



        }

        private void button1_Click(object sender, EventArgs e)
        {
            //ChangeDbDeviceStatus("Fiber3","048", "温感");
            //dsc.ChangeDeviceStatus("Fiber3", "048", "温感", "Fiber",DateTime.Now.ToString());

            //InsertDbAlarm(deviceId, AlarmInfo.AlarmTime, AlarmInfo.AlarmType);
            //string tempinfo = "\r\n手报  ::  11:12:31 05/04/2018 控制盘:01  卡:03  器件:0129\r\n灌林岩山隧道 手报07号\r\n";
            //string[] preresult = Regex.Split(tempinfo, "\r\n", RegexOptions.IgnoreCase);
            //string[] result = Regex.Split(preresult[1], " ", RegexOptions.IgnoreCase);

            //string[] alarmStringSplited = result;
            //string AlarmType = result[0];
            //DateTime AlarmTime = DateTime.ParseExact(result[4] + " " + result[5], "HH:mm:ss MM/dd/yyyy", System.Globalization.CultureInfo.CurrentCulture);
            //string ControlPanel = result[6].Split(':')[1];
            //string Card = result[8].Split(':')[1];
            //string Device = result[10].Split(':')[1];

            //string a = "";

            textBox1.Text= dsc.ChangeDeviceStatus("FCMS2", "090", "正常", "FCMS", DateTime.Now.ToString()).ToString();
        }

        private void resetButton_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("本功能可以手动恢复火灾报警信息\r\n报警主机恢复时如果与本机断开联系，方可使用本功能。\r\n您确定要恢复火灾报警信息吗？", "确认恢复火灾报警设备信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
            if(dr==DialogResult.Cancel)
            {
                return;
            }
            string deviceId;
            string devicetype;
            foreach (var item in FireAlarmTable.dtFireAlarmTable.AsEnumerable())
            {
                deviceId = item["DeviceID"].ToString();
                devicetype = item["TypeID"].ToString();
                switch (devicetype)
                {
                    case "FD":
                        {

                            try
                            {
                                dsc.ChangeDeviceStatusAsync(deviceId, "040", "正常", devicetype, DateTime.Now.ToString());
                                ChangeDbDeviceStatus(deviceId, "040", "正常");
                            }
                            catch { }

                        }
                        break;
                    case "Somke":
                        {

                            try
                            {
                                dsc.ChangeDeviceStatusAsync(deviceId, "046", "正常", devicetype, DateTime.Now.ToString());
                                ChangeDbDeviceStatus(deviceId, "046", "正常");
                            }
                            catch { }

                        }
                        break;
                    case "Fiber":
                        {

                            try
                            {
                                dsc.ChangeDeviceStatusAsync(deviceId, "049", "正常", devicetype, DateTime.Now.ToString());
                                ChangeDbDeviceStatus(deviceId, "049", "正常");
                            }
                            catch { }

                        }
                        break;
                }

            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //dsc.ChangeDeviceStatusAsync("PLC1", "060", "正常", "LC", DateTime.Now.ToString());

            AlarmAnalysis aa = new AlarmAnalysis("\r\n手报  ::  11:12:31 05/04/2018 控制盘:01  卡:03  器件:0129\r\n灌林岩山隧道 手报07号\r\n");
            
        }
    }
}
